package com.wkbb.sports.controller;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.wkbb.common.dto.basic.ClassInfoDto;
import com.wkbb.sports.dto.DetectStuChartDto;
import com.wkbb.sports.model.HlifeDetectStudent;
import com.wkbb.sports.model.HlifeDevice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.excel.util.StringUtils;
import com.github.pagehelper.PageInfo;
import com.wkbb.common.base.BaseController;
import com.wkbb.common.constants.ErrorCode;
import com.wkbb.common.constants.VersionConstant;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.basic.UserDto;
import com.wkbb.sports.dto.DeviceDto;
import com.wkbb.sports.feign.BasicFeignService;
import com.wkbb.sports.model.HlifeDetect;
import com.wkbb.sports.service.DetectService;
import com.wkbb.sports.service.TrainService;
import com.wkbb.sports.utils.DateUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;


@RestController
@Api(description = "监测管理")
@RequestMapping("/sports/{apiVersion}/detect")
@Slf4j
public class DetectController extends BaseController {

    @Autowired
    private TrainService trainService;
    @Autowired
    private DetectService detectService;
    @Autowired
    BasicFeignService basicFeignService;

    @ApiOperation(value = "新增检测")
    @RequestMapping(value = "/addDetect", method = RequestMethod.POST)
    public ResultDTO<?> addDetect(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学校ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "年级ID", required = true) @RequestParam(name = "gradeId", required = true) Long gradeId,
            @ApiParam(value = "班级ID", required = true) @RequestParam(name = "classId", required = true) Long classId,
            @ApiParam(value = "老师ID", required = true) @RequestParam(name = "teacherId", required = true) Long teacherId,
            @ApiParam(value = "项目类型ID", required = true) @RequestParam(name = "projectKind", required = true) Byte projectKind,
            @ApiParam(value = "组名", required = true) @RequestParam(name = "groupName", required = true) String groupName,
            @ApiParam(value = "上课表ID") @RequestParam(name = "teachCourseId", required = false) Long teachCourseId) {
        UserDto userDto = this.getUserByLogin();
        if (null == userDto) {
            return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
        }
        //train.setCreateBy(userDto.getName());
        Map<String, Object> params = new HashMap<>();
        params.put("orgId", orgId);
        params.put("classId", classId);
        params.put("projectKind", projectKind);
        params.put("teacherId", teacherId);
        params.put("groupName", groupName);
        List<HlifeDevice> devices;
        HlifeDetect result;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            HlifeDetect olddetect = detectService.isExit(classId);
            if (null != olddetect) {
                detectService.cancelDetect(olddetect.getId());
            }
            devices = trainService.queryOrgDeviceList(params);
            HlifeDetect hlifeDetect = new HlifeDetect();
            hlifeDetect.setOrgId(orgId);
            hlifeDetect.setGradeId(gradeId);
            ClassInfoDto classInfoDto = basicFeignService.getClassInfo(orgId, classId).getData();
            hlifeDetect.setGradeName(classInfoDto.getGradeName());
            hlifeDetect.setClassId(classId);
            hlifeDetect.setClassName(classInfoDto.getClassName());
            hlifeDetect.setGroupId(groupName);
            hlifeDetect.setTeacherId(teacherId);
//            hlifeDetect.setDetectCount(basicFeignService.getStudentInfoListByClassId(orgId, classId).getData().size());
            hlifeDetect.setDetectDate(new Date());
            hlifeDetect.setStartTime(sdf.parse(DateUtil.getDateTime()));
            hlifeDetect.setStatus((byte) 1);
            hlifeDetect.setCreateTime(sdf.parse(DateUtil.getDateTime()));
            hlifeDetect.setCreateBy(userDto.getName());
            hlifeDetect.setTeachCourseId(teachCourseId);
            //1-12年级ID对应区间40-51  年龄对应7-18岁
            hlifeDetect.setGradeAge(gradeId.intValue() - 33);
            result = detectService.addDetect(hlifeDetect, projectKind, devices, params);

        } catch (Throwable e) {
            logError(e);
            return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
        }
        return new ResultDTO<>(result);
    }

    @ApiOperation(value = "结束检测")
    @RequestMapping(value = "/cancelDetect", method = RequestMethod.POST)
    public ResultDTO<?> cancelDetect(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "监测ID", required = true) @RequestParam(name = "detectId", required = true) Long detectId) {
        UserDto userDto = this.getUserByLogin();
        if (null == userDto) {
            return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
        }
        try {
            detectService.cancelDetect(detectId);
        } catch (Throwable e) {
            logError(e);
            return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
        }
        return new ResultDTO<>();
    }

    @ApiOperation(value = "查询检测")
    @RequestMapping(value = "/selectDetect", method = RequestMethod.POST)
    public ResultDTO<?> selectDetect(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "监测ID", required = true) @RequestParam(name = "detectId", required = true) Long detectId) {
        UserDto userDto = this.getUserByLogin();
        if (null == userDto) {
            return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
        }
        //train.setCreateBy(userDto.getName());
        HlifeDetect hlifeDetect = null;
        try {
            hlifeDetect = detectService.selDetecInfo(detectId);
        } catch (Throwable e) {
            logError(e);
            return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
        }
        return new ResultDTO<HlifeDetect>(hlifeDetect);
    }

    @ApiOperation(value = "查询心率结果图表数据")
    @RequestMapping(value = "/getDetectChartData", method = RequestMethod.GET)
    public ResultDTO<HlifeDetect> getDetectChartData(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "监测ID", required = true) @RequestParam(name = "detectId", required = true) Long detectId) {
        UserDto userDto = this.getUserByLogin();
        if (null == userDto) {
            return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
        }
        HlifeDetect hlifeDetect = null;
        try {
            hlifeDetect = detectService.getDetectChartData(detectId);
        } catch (Throwable e) {
            logError(e);
            return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
        }
        return new ResultDTO<>(hlifeDetect);
    }

    @ApiOperation(value = "查询个人心率结果图表数据")
    @RequestMapping(value = "/getStuDetectChartData", method = RequestMethod.GET)
    public ResultDTO<DetectStuChartDto> getStuDetectChartData(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "监测ID", required = true) @RequestParam(name = "detectId", required = true) Long detectId,
            @ApiParam(value = "学生ID", required = true) @RequestParam(name = "studentId", required = true) Long studentId) {
        UserDto userDto = this.getUserByLogin();
        if (null == userDto) {
            return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
        }
        DetectStuChartDto dto = null;
        try {
            dto = detectService.getStuDetectChartData(detectId,studentId);
        } catch (Throwable e) {
            logError(e);
            return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
        }
        return new ResultDTO<>(dto);
    }

    @ApiOperation(value = "查询检测列表")
    @RequestMapping(value = "/selectDetectList", method = RequestMethod.POST)
    public ResultDTO<?> selectDetectList(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "老师ID") @RequestParam(name = "teacherId", required = false) Long teacherId, @ApiParam(value = "分页数", defaultValue = "0") @RequestParam(name = "pageNo") int pageNo,
            @ApiParam(value = "分页大小", defaultValue = "20") @RequestParam(name = "pageSize") int pageSize) {
        UserDto userDto = this.getUserByLogin();
        if (null == userDto) {
            return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
        }
        //train.setCreateBy(userDto.getName());
        Map<String, Object> params = new HashMap<>();
        params.put("teacherId", teacherId);

        PageInfo<HlifeDetect> hlifeDetects = null;
        try {
            hlifeDetects = detectService.queryDetectList(params, pageNo, pageSize);
        } catch (Throwable e) {
            logError(e);
            return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
        }
        return new ResultDTO<PageInfo<HlifeDetect>>(hlifeDetects);
    }

    @ApiOperation(value = "查询在使用的组别")
    @RequestMapping(value = "/selectUseDeviceGoup", method = RequestMethod.GET)
    public ResultDTO<?> selectUseDeviceGoup(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学校ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "项目类型", required = false) @RequestParam(name = "projectKind", required = false) Byte projectKind) {
        UserDto userDto = this.getUserByLogin();
        if (null == userDto) {
            return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
        }
        List<String> group;
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("orgId", orgId);
            if (StringUtils.isEmpty(projectKind)) {
                map.put("projectKind", 5);
            }
            group = detectService.selectUseDeviceGoup(map);
        } catch (Throwable e) {
            logError(e);
            return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
        }
        return new ResultDTO<List<String>>(group);
    }

    private void logError(Throwable e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        pw.flush();
        log.error(sw.toString());
    }

}
